//
//  BRWelcomeVC.m
//  standard
//
//  Created by 甘卫国 on 2025/1/17.
//

#import "BRWelcomeVC.h"

#import "BRPopoverView.h"
#import "GXJWebViewController.h"

@interface BRWelcomeVC ()
{
    UIButton *_biometyBtn;
    UIButton *_policyBtn;
}

@property (nonatomic,strong) BRLoginRecordView *recordView;;


@property (nonatomic,weak) BRPopoverView *popView;

@property (nonatomic,strong) UIView *faceIdbg;

@property (nonatomic,strong) UIScrollView *sView;

@end

@implementation BRWelcomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
  
    [self biometyBtnShow]; //face登录
    
    [self br_checkRecord];
}

- (void)br_hidden {
    
    CGFloat w = kScreenWidth;
    [UIView animateWithDuration:0.25 animations:^{
           
        self.view.transform = CGAffineTransformMakeTranslation(-w, 0);
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)br_show {
    
    
    
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformMakeRotation(0);
    }];
}

#pragma mark --点击事件
- (void)loginClick:(UIControl *)btn {
    
    NSInteger tag = btn.tag - 600;

    if (!self.isAgreed) {
      
        if (self.popView) {
            return;
        }
        
        self.popView = [BRPopoverView showText:Localized(@"toast_agreeTermUsePP") inView:self.view relateView:_policyBtn direction:YES];
        return;
    }
    
    if (tag < 2) {
        [self br_hidden];
    }
    if (self.loginClickBlock) {
        self.loginClickBlock(tag);
    }
   
    
}

- (void)br_hiddenBiomeBtn {
    self.faceIdbg.hidden = YES;
}


- (void)biometyBtnShow {
    BOOL isShow = [GGFaceIdManManage gg_showBtn];
  
    self.faceIdbg.hidden = !isShow;
    WS(weakSelf);
    [GGFaceIdManManage gg_checkFaceAction:^{

    } faile:^(NSInteger code) {
        // 单独处理被锁定后隐藏
        if (@available(iOS 11.0, *)) {
            if (code == LAErrorBiometryLockout) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                    weakSelf.faceIdbg.hidden = YES;
                }];

            }
        }
    }];
}


- (void)br_checkRecord {
    
    BOOL has = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLoginTypeKey"];
    self.recordView.hidden = !has;
    if (has) {
        [self br_updateRecordY:[BRUserManager share].loginType];
    }
}

- (void)br_updateRecordY:(NSInteger)tag {
    
    
    BRLoginBtn *btn = [self.view viewWithTag:tag + 600];
    
    [self.recordView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btn.mas_right).offset(-24);
        make.top.equalTo(btn.mas_top).offset(-10);
    }];
    
}


- (BOOL)isAgreed {
    return _policyBtn.isSelected;
}

- (void)policyClick1:(NSInteger)type {
    [self.view endEditing:YES];
    
    // 使用新的协议URL生成方法，根据当前语言动态生成
    NSString *url = [BRTools br_agreementURLWithType:type];
    NSString *titleStr = Localized(@"set_terms");
    if (type == 1) {
        titleStr = Localized(@"set_privacy");
    }
    GXJWebViewController *webView = [[GXJWebViewController alloc] init];
    webView.url = url ;
    [webView initWhiteBarWithTitle:titleStr isBack: YES];
    webView.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:webView animated:YES completion:nil];
}

- (void)clickPolicyBtn:(UIButton *)btn {
    _policyBtn.selected = !_policyBtn.selected;
    if (self.popView) {
        [self.popView removeFromSuperview];
        self.popView = nil;
    }
}

- (void)clickLoginByFaceID {
    
    if (!self.isAgreed) {
      

        if (self.popView) {
            return;
        }
        
        self.popView = [BRPopoverView showText:Localized(@"toast_agreeTermUsePP") inView:self.view relateView:_policyBtn direction:YES];
        return;
    }
    
    if (self.loginClickBlock) {
        self.loginClickBlock(4);
    }
}


#pragma mark - UI --
- (void)setUI {
    
    self.view.backgroundColor = UIColorWhite;
    
    UIScrollView *sView = [[UIScrollView alloc] init];
    sView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    [self.view addSubview:sView];
    [sView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    
    UIView *contView = [[UIView alloc] init];
    [sView addSubview:contView];
    [contView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KStatusBarHeight);
        make.left.right.bottom.offset(0);
        make.width.mas_equalTo(kScreenWidth);
    }];
    
    UIImageView *logo = [[UIImageView alloc] initWithImage:UIImageMake(@"AppLogo")];
    [contView addSubview:logo];
    [logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(44);
        make.centerX.offset(0);
        make.width.height.mas_equalTo(88);
        
    }];
    
    QMUILabel *welcomeL = [[QMUILabel alloc] init];
    welcomeL.font = [UIFont br_fontB:28];
    welcomeL.textColor = kColorMain;
    welcomeL.text = Localized(@"login_welcomeTitle");
    [contView addSubview:welcomeL];
    [welcomeL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(logo.mas_bottom).offset(8);
        make.centerX.equalTo(self.view);
        make.height.mas_greaterThanOrEqualTo(34);
    }];
    
    UIStackView *stack = [[UIStackView alloc] init];
    stack.axis = UILayoutConstraintAxisVertical;
    stack.spacing = 14;
    [contView addSubview:stack];
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(welcomeL.mas_bottom).offset(28);
        make.left.offset(28);
        make.right.offset(-28);
    }];
    
    UIView *orView = [[UIView alloc] init];
    UIColor *orColor = kColorD2D8E2;
    QMUILabel *orLa = [BRToolsView br_label:Localized(@"login_or") textColor:kColorD2D8E2 font:[UIFont fontR:20] textAlignment:NSTextAlignmentCenter];
    [orView addSubview:orLa];
    [orLa mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.centerY.offset(0);
       
        make.height.mas_greaterThanOrEqualTo(20);
    }];
    
    for (int i = 0; i < 2; i++) {
        UIView *orLine = [[UIView alloc] init];
        orLine.backgroundColor = orColor;
        [orView addSubview:orLine];
        [orLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(orLa.mas_centerY);
            make.height.mas_equalTo(0.5);
            if (i == 0) {
                make.left.offset(0);
                make.right.equalTo(orLa.mas_left).offset(-12);
            }else {
                make.right.offset(0);
                make.left.equalTo(orLa.mas_right).offset(12);
            }
        }];
    }
    
    
    
    // 暂时只保留手机号登录，其他登录方式先注释掉
    NSArray *titls = @[Localized(@"login_withPhone")/*,Localized(@"login_withEmail"),Localized(@"login_withGoogle"),Localized(@"login_withApple")*/];
    NSArray *imgs = @[@"login_withPhone"/*,@"login_withEmail",@"login_withGoogle",@"login_withApple"*/];
    
    for (int i = 0; i < imgs.count; i++) {
        
        BRLoginBtn *loginBtn = [[BRLoginBtn alloc] init];
        loginBtn.img.image = UIImageMake(imgs[i]);
        loginBtn.titleL.text = titls[i];
        
        [stack addArrangedSubview:loginBtn];
        loginBtn.tag = 500 + i;
        
        UIControl *btn = [[UIControl alloc] init];
        btn.tag = 600 + i;
        [loginBtn addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.offset(0);
        }];
        [btn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
        
        
        if (i == 3) {
            if (@available(iOS 13.0, *)) {
                
            } else {
                // Fallback on earlier versions 非13后版本隐藏苹果登录按钮
                loginBtn.hidden = YES;
            }
        }
       
        
        // 暂时只保留手机号登录，不需要"或"分隔线
        /*
        if (i == 1) {
            [stack addArrangedSubview:orView];
            [orView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(40);
            }];
        }
        */
        
    }
    
    // --- 生物识别登录按钮 ---
    UIView *faceIdbg = [UIView new];
    faceIdbg.backgroundColor = UIColor.clearColor;
    faceIdbg.hidden = YES;
    NSString *biomeImgStr = [GGFaceIdManManage gg_platformType] == 2 ? @"login_faceid" : @"login_touchid";
    UIButton *faceBtn = [UIButton buttonWithType:UIButtonTypeCustom];

    [faceBtn setImage:UIImageMake(biomeImgStr) forState:UIControlStateNormal];
    
    [faceBtn addTarget:self action:@selector(clickLoginByFaceID) forControlEvents:UIControlEventTouchUpInside];

    _biometyBtn = faceBtn;
   
    [faceIdbg addSubview:_biometyBtn];
    [_biometyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(60);
        make.centerX.offset(0);
        make.bottom.offset(0);
        make.top.offset(30);
    }];
    
    _faceIdbg = faceIdbg;
    [stack addArrangedSubview:faceIdbg];
    
    self.recordView.hidden = YES;
    [contView addSubview:self.recordView];
    [self.recordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(stack.mas_right).offset(-24);
        make.top.offset(100);
    }];
    
    // 协议
    
    WS(weakSelf);
    YYLabel *resendLabel = [YYLabel new];
    resendLabel.font = [UIFont fontM:12];
    resendLabel.numberOfLines = 0;
    resendLabel.preferredMaxLayoutWidth = kScreenWidth - 74.;//100
    
    
    UIColor *selColot = kColorMain;

    NSString *termsStr = Localized(@"set_terms");
    NSString *privacyStr = Localized(@"set_privacy");
    NSString *agreeStr = [NSString stringWithFormat:Localized(@"login_agreeTo"),termsStr,privacyStr];
    
    NSMutableAttributedString *resebdStr = [[NSMutableAttributedString alloc] initWithString: agreeStr];
    resendLabel.text = agreeStr;
    [resendLabel sizeToFit];
    
    NSRange rang1 = [agreeStr rangeOfString:termsStr];
    NSRange rang2 = [agreeStr rangeOfString:privacyStr];
    
    // 设置整体颜色和字体（默认颜色）
    UIColor *defaultColor = UIColorText1; // 使用默认文字颜色
    resebdStr.yy_color = defaultColor;
    resebdStr.yy_font = [UIFont br_fontM:12];
    
    // 将"用户协议"和"隐私政策"文字设置为橙色，让用户知道可以点击
    UIColor *orangeColor = [UIColor colorWithRed:255.0/255.0 green:165.0/255.0 blue:0.0/255.0 alpha:1.0]; // 橙色
    [resebdStr yy_setColor:orangeColor range:rang1];
    [resebdStr yy_setColor:orangeColor range:rang2];
    
    [resebdStr addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:rang2];
    [resebdStr addAttribute:NSUnderlineColorAttributeName value:selColot range:rang2];
    [resebdStr yy_setTextHighlightRange:rang1 color:selColot backgroundColor:UIColor.whiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        [weakSelf policyClick1:0];
        NSLog(@"0");
    }];

    [resebdStr yy_setTextHighlightRange:rang2 color:orangeColor backgroundColor:UIColor.whiteColor tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"1");
        [weakSelf policyClick1:1];
    }];
    
    [contView addSubview:resendLabel];
    [resendLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(46);
        make.right.offset(-28);
        make.top.equalTo(stack.mas_bottom).offset(25);
        make.bottom.offset(-30);
    }];
    resendLabel.attributedText = resebdStr;
    
    UIButton *policyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [policyBtn setImage:[UIImage imageNamed:@"login_ic_check_unselected"] forState:UIControlStateNormal];
    [policyBtn setImage:[UIImage imageNamed:@"login_ic_check_selected"] forState:UIControlStateSelected];
    [contView addSubview:policyBtn];
    [policyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(10);
        make.top.equalTo(resendLabel.mas_top).offset(2.5);
        make.left.offset(30);
    }];

    policyBtn.userInteractionEnabled = NO;
    _policyBtn = policyBtn;
    
    UIControl *btn = [[UIControl alloc] init];
    [contView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(policyBtn);
        make.width.height.mas_equalTo(50);
        make.top.equalTo(policyBtn.mas_top).offset(-5);
    }];
    [btn addTarget:self action:@selector(clickPolicyBtn:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (BRLoginRecordView *)recordView {
    
    if (_recordView == nil) {
        _recordView = [[BRLoginRecordView alloc] init];
    }
    return _recordView;
}

@end



@implementation BRLoginBtn

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

#pragma mark - UI --
- (void)setUI {
    

    
    self.layer.cornerRadius = 5;
    self.layer.masksToBounds = YES;

    self.backgroundColor = UIColorMakeWithHex(@"#F7F7F9");
    
    self.titleL = [BRToolsView br_label:@"--" textColor:kColorTitle font:[UIFont br_fontR:17]];
    self.img = [[UIImageView alloc] init];
    
    [self addSubview:self.img];
    [self.img mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(10);
        make.bottom.offset(-10);
        make.left.offset(56);
        make.width.height.mas_equalTo(32);
    }];
    
    [self addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.img.mas_right).offset(16);
        make.right.offset(-6);
        make.centerY.offset(0);
    }];
    self.titleL.adjustsFontSizeToFitWidth = YES;
}

@end

@implementation BRLoginRecordView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

#pragma mark - UI --
- (void)setUI {
    
    self.backgroundColor = UIColor.clearColor;
    
    self.contV = [[UIView alloc] init];
    self.contV.backgroundColor = kColorMain;
    self.contV.layer.cornerRadius = 10;
    self.contV.layer.masksToBounds = YES;
    [self addSubview:self.contV];
    [self.contV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.offset(-4);
        make.height.mas_equalTo(20);
    }];
    
    QMUILabel *rL = [BRToolsView br_label:Localized(@"login_recent") textColor:kUIColorMainTint font:[UIFont br_fontR:12]];
    [self.contV addSubview:rL];
    [rL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(8);
        make.right.offset(-8);
        make.centerY.offset(0);
    }];
    
    UIImageView *bImg = [[UIImageView alloc] initWithImage:UIImageMake(@"login_extrusion")];
    [self addSubview:bImg];
    [bImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.height.mas_equalTo(4);
        make.left.offset(16);
        make.width.mas_equalTo(4);
    }];
    
    self.titleL = rL;
    self.bImage = bImg;
}



@end
